﻿using UnityEngine;
using UnityEngine.Networking;

namespace xres
{

    public class AsyncCopyInternalFile : BaseAsyncAction
    {

        public const string Err_Load_Internal = "Err_Load_Internal";
        public const string Err_Write_External = "Err_Write_External";


        FileCopyHandler _copyHandler;

        string _filePath = "";

        AsyncOperation _op;


        public long CheckCopyBytes()
        {
            switch (_state)
            {
            case BaseAsyncActionState.Init:
                return 0;

            case "InCopy":
                if (_copyHandler.TotalBytes > 0)
                    return _copyHandler.HaveDownBytes;
                return 0;
            }

            return _copyHandler.HaveDownBytes;
        }

        public float CheckProgress()
        {
            switch (_state)
            {
            case BaseAsyncActionState.Init:
                return 0;

            case "InCopy":
                return _op.progress;
            }

            return 1;
        }

        public bool Copy(string filePath)
        {
            switch (_state)
            {
            case BaseAsyncActionState.Init:
            case BaseAsyncActionState.Finish:
                //可用于重复执行任务
                break;

            default:
                return false;
            }

            _filePath = filePath;

            _state = "InCopy";

            var internalPath = ResPath.BuildInternalBundlePath(filePath);
            var externalPath = ResPath.BuildExternalBundlePath(filePath);

            if (false) Debug.Log($"CopyInternalFile: {filePath}");

            var webReq = UnityWebRequest.Get(internalPath);
            _copyHandler = new FileCopyHandler(externalPath); //必须每次都new, 缓存的方式行不通

            webReq.downloadHandler = _copyHandler;
            var op = webReq.SendWebRequest();
            _op = op;
            op.completed += OnComplete_Copy;

            return true;
        }

        void OnComplete_Copy(AsyncOperation op)
        {
            if (false) Debug.Log($"CopyInternalFile: OnComplete_Copy: {_filePath}");
            _op = null;

            var request = (UnityWebRequestAsyncOperation)op;
            var webReq = request.webRequest;
            using (webReq)
            {
                var setNull = true;
                if (!string.IsNullOrEmpty(webReq.error))
                {
                    if (!string.IsNullOrEmpty(_copyHandler.ErrType))
                        SetError(Err_Write_External, $"copy internal file fail");
                    else
                        SetError(Err_Load_Internal, $"copy internal file fail");

                    Debug.LogError(ErrMsg);
                    SetFinishAndNotify(ErrMsg);
                    //UserData.obj = null;
                    return;
                }

                SetError("", "");
                SetFinishAndNotify("");
                //UserData.obj = null;

                //CheckCopyBytes要用
                /*
                if (setNull)
                {
                    _downloadHandler = null;
                }
                */
            }
        }
        

    } //end of class


}



/*
 void CopyOnThread(object state)
        {
            var error = "";
            try
            { 
                File.Copy(_srcPath, _dstPath, true);
                error = "";
            }
            catch (Exception ex)
            {
                error = ex.Message;
                Debug.Log($"file copy fail: {ex.Message}");
            }

            MainThreadSync.QueueOnMainThread(OnComplete_Copy, null, error);
        }

        void OnComplete_Copy(MainThreadSync.Context ctxt)
        {
            Error = ctxt.str;
            SetFinishAndNotify(Error);
        }
        */
